package leetcode.templates.bits;

public class MaxBitsSwapPart {

	public MaxBitsSwapPart(int part, int partLen) {
		this.part = part;
		this.partLen = partLen;
		this.range = part * partLen;
		this.limit = (1 << range) - 1;
		this.one = (1 << partLen) - 1;
	}

//	int limit = 0b111111111111111111;
//	int one = 0b111;
	int part = 6;// 6段
	int partLen = 3;// 每段size3
	int range = part * partLen;
	int limit = (1 << range) - 1;
	int one = (1 << partLen) - 1;

	public int swap(int status, int a, int b) {
		int numa = pick(status, a);
		int numb = pick(status, b);
		status = clear(status, a, b);
		status = add(status, b, numa);
		status = add(status, a, numb);
		return status & limit;// 根据数据是否严格 & 可有可无
	}

	// status的a段加上muna状态。段从左到右依次是0，1，2，3，4，5，每一段是三位
	private int add(int status, int a, int numa) {
		return status | (numa << move(a));
	}

	// 将status的，a，b段清空为000
	private int clear(int status, int a, Integer b) {
		status = status & clearAnd(a);
		status = status & clearAnd(b);
		return status;
	}

	private int clearAnd(int pos) {
		return (limit << (move(pos) + partLen)) | ((1 << move(pos)) - 1);
	}

	// 第pos段向左移动的步数
	private int move(int pos) {
		int ans = (part - 1 - pos) * partLen;
		return ans;
	}

	// 摘出status的pos段内容
	private int pick(int status, int pos) {
		int move = move(pos);
		int num = (one << move) & status;
		return num >> move;
	}

	public static void main(String[] args) {
		MaxBitsSwapPart mbsp = new MaxBitsSwapPart(6, 2);
		int status = 0b110_110_110_001_001_001;
		status = mbsp.swap(status, 3, 5);
		System.out.println(Integer.toBinaryString(status));
	}

}
